import 'package:demo/app/widgets/dialog_key_value.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import '../../../../../model/area_model.dart';
import '../../../../../model/company_model.dart';
import '../../../../../model/constant_model.dart';
import '../../../../../model/key_value_model.dart';
import '../../../../../model/province_model.dart';
import '../../../../../net/api_provider.dart';
import '../base_info_controller.dart';

class Tab2Controller extends GetxController {

  ApiProvider apiProvider = Get.find();
  final FocusNode focusNode = FocusNode();
  void hintKeyboard(){
    focusNode.unfocus(); // 触发焦点变化，键盘收回
  }

  @override
  void onReady() {
    super.onReady();
    getConstant(isFirst: true);
    getProvinceCity();
  }

  TextEditingController companyNameController = TextEditingController(); /// 单位名称
  Map<String, dynamic>? provinceList; /// 省份
  Map<String, dynamic>? cityList; /// 城市
  var selectProvince = KeyValue('',''); /// 选择的省份
  var selectCity = KeyValue('',''); /// 选择的市
  Rx<KeyValue> selectArea = KeyValue('','').obs; /// 选择的县
  TextEditingController companyAddressController = TextEditingController(); /// 地址
  TextEditingController companyPhoneController = TextEditingController(); /// 电话
  Map<String, dynamic>? natureList; /// 单位性质
  Rx<KeyValue> selectNature = KeyValue(0,'').obs; /// 选择的单位性质
  Map<String, dynamic>? industryList; /// 所属行业
  Rx<KeyValue> selectIndustry = KeyValue(0,'').obs; /// 选择的单位所属行业
  Map<String, dynamic>? professionList; /// 职业
  Rx<KeyValue> selectProfession = KeyValue(0,'').obs; /// 选择的职业
  Map<String, dynamic>? earnList; /// 收入类型
  Rx<KeyValue> selectEarn = KeyValue(0,'').obs; /// 选择的收入类型
  Map<String, dynamic>? amountList; /// 月收入
  Rx<KeyValue> selectAmount = KeyValue(0,'').obs; /// 选择的月收入

  /// 获取配置的列表
  void getConstant({bool isFirst = false}) async{
    var result = await apiProvider.getData({}, ApiProvider.constant);
    if(result.code == 200){
      var constant = Constant.fromJson(result.data);
      natureList = constant.companyList;
      industryList = constant.industryList;
      professionList = constant.professionList;
      earnList = constant.earnList;
      amountList = constant.amountList;

      if(isFirst){
        getJobDetail();
      }
    }
  }

  /// 获取省份、城市
  void getProvinceCity() async{
    var result = await apiProvider.getData({}, ApiProvider.province);
    if(result.code == 200){
      var province = Province.fromJson(result.data);
      provinceList = province.provinceList;
      cityList = province.cityList;
    }
  }

  /// 获取工作信息
  void getJobDetail() async {
    var result = await apiProvider.getData({}, ApiProvider.job_detail);
    if(result.code == 200){
      var company = Company.fromJson(result.data);
      companyNameController.text = company.companyName; /// 单位名称
      if (company.companyProvinceCode.isNotEmpty && company.companyProvince.isNotEmpty){
        selectProvince = KeyValue(company.companyProvinceCode,company.companyProvince); /// 选择的省份
      }
      if (company.companyCityCode.isNotEmpty && company.companyCity.isNotEmpty){
        selectCity = KeyValue(company.companyCityCode,company.companyCity); /// 选择的市
      }
      if (company.companyAreaCode.isNotEmpty && company.companyArea.isNotEmpty){
        selectArea.value = KeyValue(company.companyAreaCode,company.companyArea); /// 选择的县
      }
      companyAddressController.text = company.companyAddress; /// 地址
      companyPhoneController.text = company.companyTelephone; /// 电话
      if(company.companyNatureId > 0 && natureList != null){
        for(var entry in natureList!.entries) {
          if (entry.key == '${company.companyNatureId}'){
            selectNature.value = KeyValue(int.tryParse(entry.key) ?? 0,entry.value); /// 选择的单位性质
          }
        }
      }
      if(company.industryId > 0 && industryList != null){
        for(var entry in industryList!.entries) {
          if (entry.key == '${company.industryId}'){
            selectIndustry.value = KeyValue(int.tryParse(entry.key) ?? 0,entry.value); /// 选择的单位所属行业
          }
        }
      }
      if(company.positionId > 0 && professionList != null){
        for(var entry in professionList!.entries) {
          if (entry.key == '${company.positionId}'){
            selectProfession.value = KeyValue(int.tryParse(entry.key) ?? 0,entry.value); /// 职业
          }
        }
      }
      if(company.earnId > 0 && earnList != null){
        for(var entry in earnList!.entries) {
          if (entry.key == '${company.earnId}'){
            selectEarn.value = KeyValue(int.tryParse(entry.key) ?? 0,entry.value); /// 收入类型
          }
        }
      }
      if(company.amountId > 0 && amountList != null){
        for(var entry in amountList!.entries) {
          if (entry.key == '${company.amountId}'){
            selectAmount.value = KeyValue(int.tryParse(entry.key) ?? 0,entry.value); /// 选择的月收入
          }
        }
      }
    }
  }

  /// 选择省份
  void chooseProvince(){
    hintKeyboard();
    if(provinceList == null || cityList == null){
      getProvinceCity();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(provinceList, (proCode,proValue){
        var s = proCode.substring(0,2);
        Map<String, dynamic> list = {};
        cityList!.forEach((key, value) {
          if(key.startsWith(s)){
            list[key] = value;
          }
        });

        Future.delayed(const Duration(milliseconds: 100), () {
          Get.bottomSheet(
            DialogKeyValue(list, (cityCode,cityValue) async {
              var result = await apiProvider.getData({'code':cityCode}, ApiProvider.area);
              if(result.code == 200){
                var area = Area.fromJson(result.data);
                Get.bottomSheet(
                  DialogKeyValue(area.area_list, (areaCode,areaValue) {
                    selectProvince = KeyValue(proCode, proValue);
                    selectCity = KeyValue(cityCode,cityValue); // 选择的市
                    selectArea.value = KeyValue(areaCode,areaValue); // 选择的县
                  }),
                );
              }
            }),
          );
        });
      }),
    );
  }

  /// 选择单位性质
  void chooseNature() {
    hintKeyboard();
    if(natureList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(natureList!, (code,value){
        selectNature.value = KeyValue(int.tryParse(code) ?? 0, value);
      }),
    );
  }

  /// 所属行业
  void chooseIndustry() {
    hintKeyboard();
    if(industryList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(industryList!, (code,value){
        selectIndustry.value = KeyValue(int.tryParse(code) ?? 0,value);
      }),
    );
  }

  /// 选择职业
  void chooseProfession() {
    hintKeyboard();
    if(professionList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(professionList, (code,value){
        selectProfession.value = KeyValue(int.tryParse(code) ?? 0,value);
      }),
    );
  }

  /// 收入类型
  void chooseEarn() {
    hintKeyboard();
    if(earnList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(earnList, (code,value){
        selectEarn.value = KeyValue(int.tryParse(code) ?? 0,value);
      }),
    );
  }

  /// 月收入
  void chooseAmount() {
    hintKeyboard();
    if(amountList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(amountList, (code,value){
        selectAmount.value = KeyValue(int.tryParse(code) ?? 0,value);
      }),
    );
  }

  /// 上一步
  void back() {
    BaseInfoController c = Get.find();
    c.setCurrentIndex(0);
  }

  /// 提交
  void submit() async{
    if (companyNameController.text.isEmpty || companyNameController.text.length < 4){
      EasyLoading.showToast('请填写正确的单位名称');
      return;
    }
    if (selectProvince.key.isEmpty || selectProvince.value.isEmpty || selectCity.key.isEmpty || selectCity.value.isEmpty || selectArea.value.key.isEmpty || selectArea.value.value.isEmpty){
      EasyLoading.showToast('请选择单位所在城市');
      return;
    }
    if (companyAddressController.text.isEmpty || companyAddressController.text.length < 4){
      EasyLoading.showToast('请检查单位地址');
      return;
    }
    if (companyPhoneController.text.isEmpty || companyPhoneController.text.length < 4){
      EasyLoading.showToast('请输入单位电话');
      return;
    }
    if (selectNature.value.key == 0 || '${selectNature.value.value}'.isEmpty){
      EasyLoading.showToast('选择的单位性质');
      return;
    }
    if (selectIndustry.value.key == 0 || '${selectIndustry.value.value}'.isEmpty){
      EasyLoading.showToast('请选择所属行业');
      return;
    }
    if (selectProfession.value.key == 0 || '${selectProfession.value.value}'.isEmpty){
      EasyLoading.showToast('请选择职业');
      return;
    }
    if (selectEarn.value.key == 0 || '${selectEarn.value.value}'.isEmpty){
      EasyLoading.showToast('请选择收入类型');
      return;
    }
    if (selectAmount.value.key == 0 || '${selectAmount.value.value}'.isEmpty){
      EasyLoading.showToast('请选择您的月收入');
      return;
    }

    Map<String, dynamic> obj = {
      'company_name' : companyNameController.text,
      'company_province_code' : selectProvince.key,
      'company_province' : selectProvince.value,
      'company_city_code' : selectCity.key,
      'company_city' : selectCity.value,
      'company_area_code' : selectArea.value.key,
      'company_area' : selectArea.value.value,
      'company_address' : companyAddressController.text,
      'company_telephone' : companyPhoneController.text,
      'company_nature_id' : selectNature.value.key, // 单位性质
      'industry_id' : selectIndustry.value.key, // 所属行业
      'position_id' :selectProfession.value.key,
      'earn_id' : selectEarn.value.key,
      'amount_id' : selectAmount.value.key
    };
    var result = await apiProvider.getData(obj, ApiProvider.job_updated);
    if(result.code == 200){
      BaseInfoController c = Get.find();
      c.setCurrentIndex(2);
    }
  }
}
